import type { FileInfo } from '#/api/openapi';

import { downloadFileFromUrl } from '@vben/utils';

import { client } from '#/api';
import { useFilesStore } from '#/store/files';

// 下载文件
export const downloadFile = async (code: string, file: FileInfo) => {
  // 模拟下载
  console.log('下载文件:', file.fileName, 'Code:', code);
  if (file.downloadCount) {
    file.downloadCount++;
  }
  // 记录下载到 files store
  const filesStore = useFilesStore();
  if (file.id) {
    filesStore.recordFileDownload(code, file);
  }

  if (file.md5 && file.fileName) {
    const downloadLink = await client.shareItem.getShareItemFilesLink(
      code,
      file.md5,
      file.fileName,
    );
    downloadFileFromUrl({
      source: downloadLink,
      fileName: file.fileName,
      target: '_blank',
    });
  } else {
    console.error('文件缺少必要信息，无法下载:', file);
    // const { data } = await client.shareItem.getShareItemById(code);
    // if (data.code && data.files && data.fileName) {
    //   downloadFile(data.code, data);
    // } else {
    //   message.error('文件缺少必要信息，无法下载');
    // }
  }
};
